package cn.wolfcode.service.impl;

import cn.wolfcode.domain.BalanceDetail;
import cn.wolfcode.domain.UserWallet;
import cn.wolfcode.mapper.UserWalletMapper;
import cn.wolfcode.service.IBalanceDetailService;
import cn.wolfcode.service.IUserWalletService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class UserWalletServiceImpl extends ServiceImpl<UserWalletMapper, UserWallet> implements IUserWalletService{

    @Autowired
    private IBalanceDetailService balanceDetailService;

    // 根据用户ID查询用户的余额(默认钱包状态正常才能查询)
    @Override
    public UserWallet byUserId(Long userId) {
        LambdaQueryWrapper<UserWallet> wrapper = Wrappers.lambdaQuery(UserWallet.class)
                .eq(UserWallet::getUserId, userId)                                  // 用户ID
                .eq(UserWallet::getStatus, UserWallet.USER_WALLET_STATUS_NORMAL);   // 钱包状态为正常

        // 返回查询到的结果
        return getOne(wrapper);
    }

    // 支付
    // 可以写SQL语句,使用乐观锁
    // UPDATE 表名 SET balance = balance - #{payMoney} WHERE userId = #{userId} AND balance >= #{payMoney}
    @Transactional(rollbackFor = Exception.class) //事务
    @Override
    public boolean pay(Long userId, BigDecimal payMoney, String info) {

        // 得到当前用户的钱包
        UserWallet userWallet = this.byUserId(userId);

        if (userWallet == null)  {
            throw new RuntimeException("你没有开通钱包或者你的钱包状态有异常不能支付");
        }

        if (userWallet.getBalance().compareTo(payMoney) < 0) {
            throw new RuntimeException("你余额不足,无法进行支付");
        }

        // 减除100元
        userWallet.setBalance(userWallet.getBalance().subtract(payMoney));
        // 记录添加记录
        balanceDetailService.payInfo(userWallet.getId(), info, payMoney);

        // 修改
        return updateById(userWallet);
    }

    // 退款
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean refund(Long detailId, String refundInfo) {

        // 对那条信息的退款
        BalanceDetail detail = balanceDetailService.getById(detailId);
        // 添加退款记录
        balanceDetailService.refundInfo(detail, refundInfo);

        // 钱包金额增加
        UserWallet userWallet = getById(detail.getWalletId());
        userWallet.setBalance(detail.getMoney());

        return updateById(userWallet);
    }
}
